package com.amap.map.util.version;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.alibaba.fastjson.JSON;
import com.amap.map.R;
import com.amap.map.util.Configuration;
import com.amap.map.util.ToastUtil;
import com.amap.map.vo.Json;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.webkit.URLUtil;

public class VersionUpdate {
	
	 // 获得文件扩展名字符串 
    private String fileName ; 
    //进度条
    private ProgressDialog dialog ;
	
	// 调用更新的Activity 
    public Activity activity = null; 
	
	public VersionUpdate(  Activity activity  ){
		this.activity = activity ;
	}
	
    /***
     * 回調函數
     * @param notification
     * @return
     */
    public boolean notification(String notification ){
    	try {
    		Json location = JSON.parseObject( notification , Json.class);
			if( location.isSuccess() ){
			    // 弹出对话框，选择是否需要更新版本 
				fileName = location.getObj().toString() ;
				showUpdateDialog( location.getMsg() ,location.getObj().toString() ); 
			}else{
				ToastUtil.show( activity.getApplicationContext() , "当前版本是最新版本不需要更新." );
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return true ;
    }
    
    /**
     * 弹出对话框，选择是否需要更新版本
     */ 
    public void showUpdateDialog( final String url , String version ) { 
        @SuppressWarnings("unused") 
        AlertDialog alert = new AlertDialog.Builder(this.activity) 
        .setTitle("新版本").setIcon( R.drawable.ic_launcher ) 
        .setMessage(version + "\n是否需要更新？") 
        .setPositiveButton("是", new DialogInterface.OnClickListener() { 
            public void onClick(DialogInterface dialog, int which) { 
                // 通过地址下载文件 
                downloadTheFile( Configuration.UPDATE_DOWNLOAD_DEMAIN + url ); 
                // 显示更新状态，进度条 
                showWaitDialog(); 
            } 
        }).setNegativeButton("否", new DialogInterface.OnClickListener() { 
            public void onClick(DialogInterface dialog, int which) { 
                dialog.cancel(); 
            } 
        }).show(); 
    }

    /**
     * 
     * 显示更新状态，进度条
     */ 
    public void showWaitDialog() { 
    	dialog = new ProgressDialog(activity); 
        dialog.setMessage("正在更新，请稍候..."); 
        dialog.setIndeterminate(true); 
        dialog.setCancelable(true); 
        dialog.show(); 
    } 
    
    /**
     * 
     * 截取文件名称并执行下载
     * @param strPath
     */ 
    private void downloadTheFile(final String strPath) { 
        try { 
            new Thread(new Runnable() { 
                @Override 
                public void run() { 
                    // TODO Auto-generated method stub 
                    try { 
                        // 执行下载 
                    doDownloadTheFile(strPath); 
                    } catch (Exception e) { 
                        Log.e( Configuration.LOG_NAME, e.getMessage(), e); 
                        dialog.cancel(); 
                    	dialog.dismiss(); 
                    } 
                } 
            }).start(); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 
    
    /**
     * 
     * 执行新版本进行下载，并安装     * 
     * @param strPath     * 
     * @throws Exception
     */ 
    private void doDownloadTheFile(String strPath) throws Exception { 
        Log.i(  Configuration.LOG_NAME , "getDataSource()"); 
        // 判断strPath是否为网络地址 
        if (!URLUtil.isNetworkUrl(strPath)) { 
            Log.i(  Configuration.LOG_NAME , "服务器地址错误！"); 
        } else { 
        	File myTempFile = new File(Environment.getExternalStorageDirectory() +"/"+ Configuration.OUT_MAP_DOWNLOAD_ADDRESS , fileName ) ;
        	HttpClient client = new DefaultHttpClient();  
            HttpGet get = new HttpGet( strPath );  
            HttpResponse response;  
            try {  
                response = client.execute(get);  
                HttpEntity entity = response.getEntity();  
                long length = entity.getContentLength();  
                InputStream is = entity.getContent();  
                FileOutputStream fileOutputStream = null;  
                if (is != null) {   
                    fileOutputStream = new FileOutputStream( myTempFile );  
                    byte[] buf = new byte[1024];  
                    int ch = -1;  
                    int count = 0;  
                    while ((ch = is.read(buf)) != -1) {  
                        fileOutputStream.write(buf, 0, ch);  
                        count += ch;  
                        if (length > 0) {  
                        }  
                    }  
                }  
                fileOutputStream.flush();  
                if (fileOutputStream != null) {  
                    fileOutputStream.close();  
                }
            
            	Log.i( Configuration.LOG_NAME, "getDataSource() Download ok..."); 
            	dialog.cancel(); 
            	dialog.dismiss(); 
            	// 打开文件 
            	openFile(myTempFile); 
            	try { 
            		is.close(); 
            	} catch (Exception ex) { 
            		Log.e(  Configuration.LOG_NAME , "getDataSource() error: " + ex.getMessage(), ex); 
            	}
            } catch (Exception ex) { 
        		Log.e(  Configuration.LOG_NAME , "getDataSource() error: " + ex.getMessage(), ex); 
        		dialog.cancel(); 
            	dialog.dismiss(); 
            } 
        } 
    } 
 
    /**
     * 打开文件进行安装
     */ 
    private void openFile(File file) { 
    	if( file.exists() ){
    		Intent intent = new Intent(Intent.ACTION_VIEW);  
            intent.setDataAndType(Uri.fromFile( file ), "application/vnd.android.package-archive" );  
            activity.startActivity(intent);
    	}
    } 
    
}
